var mqclient = require("./mqclient");

class TMediaStreamLog {
    constructor() {
        this.logId = ['mslog', (new Date()).getTime(), parseInt(1000 * Math.random())].join('.');
        this.notifyTime = (new Date()).getTime();
        this.requestId = "";
        this.clientId = "";
        this.svrType = "";
        this.svrCode = "";
        this.appName = "";
        this.streamName = "";
        this.streamFullName = "";
        this.action = "";
        this.recName = "";
        this.recPath = "";
        this.extends = {};
    }
    static getNginxLog(psDict) {
        var res = new TMediaStreamLog();
        try {
            res.svrType = "nginx";
            res.svrCode = psDict.svrCode;
            res.appName = psDict.app;
            res.streamName = psDict.name;
            res.streamFullName = [res.svrCode, res.appName, res.streamName].join("|");
            res.requestId = ["reqId", res.svrCode, res.appName, res.streamName, (new Date()).getTime()].join('-');
            res.clientId = psDict.clientid;
            res.action = psDict.call;
            if (res.action == "record_done") {
                res.recName = psDict.recorder;
                res.recPath = psDict.path;
            }
        } catch (er) {
            console.log(er);
        }
        return res;
    }
    static getBceLog(bodyData) {
        var res = new TMediaStreamLog();
        try {
            res.svrType = "bce";
            res.svrCode = bodyData.playDomain;
            res.appName = bodyData.app;
            res.streamName = bodyData.stream;
            res.streamFullName = [res.svrCode, res.appName, res.streamName].join("|");
            res.requestId = bodyData.requestId;
            res.clientId = bodyData.sessionId;
            if (bodyData.type == "StreamingStatusChanged" && bodyData.body.current == "STREAMING") {
                res.action = "publish";
            } else if (bodyData.type == "StreamingStatusChanged" && bodyData.body.current == "NO_SOURCE") {
                res.action = "publish_done";
            } else if (bodyData.type == "ThumbnailFileGenerated") {
                res.action = "thumb";
                res.recName = bodyData.body.bucket;
                res.recPath = bodyData.body.key;
            } else if (bodyData.type == "RecordFileGenerated") {
                res.action = "record_done";
                res.recName = bodyData.body.bucket;
                res.recPath = bodyData.body.key;
            }
        } catch (er) {
            console.log(er);
        }
        return res;
    }
}
class TMediaStream {
    constructor() {
        this.config = {
            mqPs: {
                mqClientId: ['mqid', ((new Date()).getTime()).toString(), parseInt(1000 * Math.random()).toString()].join(''),
                mqUrl: "tcp://hhuciot.mqtt.iot.bj.baidubce.com:1883",
                mqUid: "hhuciot/mcu",
                mqPwd: "9vG6KT6V64S2uS3P"
            },
            msgTopic: "/hhu/mediaStream/notify"
        }
        this.mqClient = new mqclient.TMqClient();
        this.mqClient.open().then(_ => {
            console.log('connect to mq server.');
        })
    }
    regist2WebSvr(webSvr) {
        var me = this;
        if (webSvr && webSvr != null && webSvr.registRoute) {
            var respJson = function(result, response) {
                try {
                    response.send(JSON.stringify(result));
                } catch (eer) {
                    console.log(eer);
                }
            }
            webSvr.registRoute("ms", "notify", "bce", function(result, request, response) {
                try {
                    respJson(result, response);
                    var msgJson = request.body.messageBody;
                    var msgBody = JSON.parse(msgJson);
                    me.setBceLog(msgBody).then(_ => {
                        console.log(msgBody);
                    })
                } catch (err) {
                    console.log(err);
                    respJson(result, response);
                }
            });
            webSvr.registRoute("ms", "notify", "nginx", function(result, request, response) {
                respJson(result, response);
                try {
                    me.setNginxLog(result.ps).then(_ => {
                        console.log(result);
                    });
                } catch (err) {
                    console.log(err);
                }
            });
        }
    }

    setBceLog(msgBody) {
        var me = this;
        var res = {
            state: 0
        }
        return new Promise((success, faild) => {
            try {
                var msLog = TMediaStreamLog.getBceLog(msgBody);
                if (msLog.action != '') {
                    console.log(msLog);
                    me.notify(msLog);
                }
                success(msLog);
            } catch (er) {
                console.log(er);
                success(res);
            }
        })
    }
    setNginxLog(psDict) {
        var me = this;
        var res = {
            state: 0
        }
        return new Promise((success, faild) => {
            try {
                var msLog = TMediaStreamLog.getNginxLog(psDict);
                if (msLog.action != '') {
                    console.log(msLog);
                    me.notify(msLog);
                }
                success(msLog);
            } catch (er) {
                console.log(er);
                success(res);
            }
        })
    }
    notify(msLog) {
        var me = this;
        try {
            var topic = [me.config.msgTopic, msLog.svrCode, msLog.appName, msLog.streamName].join("/");
            me.mqClient.sendMsg(topic, msLog);
            console.log("notify:", topic, msLog)
        } catch (eer) {
            console.log(eer);
        }
    }

}
module.exports = {
    TMediaStream: TMediaStream,
    TMediaStreamLog: TMediaStreamLog
}